import { controller, get, post } from '../middleware/route'
import request from '../utils/request'
import iconv from 'iconv-lite'
import Province from '../database/schema/province'
import City from '../database/schema/city'
import Menu from '../database/schema/menu'
@controller('/geo')
export class Geo {
  @get('/menu')
  async getMenu(ctx, next) {
    let menu = await Menu.find({}, '-_id').exec()
    ctx.body = {
      code: menu.length ? 0 : -1,
      menu: menu.length ? menu : []
    }
  }
  @get('/getPosition')
  async getPositon(ctx, next) {
    const options = {
      url: 'http://ip.ws.126.net/ipquery',
      encoding:null,
      transform: body => { 
        return  iconv.decode(body,'gb2312')
      }
    }
    let res = await request(options)
    if (res.search(/lo/)) {
      let province = res.match(/lo="(.*?)"/)
      province = province[1].replace(/省/, '')
      let city = res.match(/lc="(.*?)"/)
      city = city[1].replace(/市/, '')
      return (ctx.body = {
        code: 0,
        province,
        city
      })
    } else {
      return (ctx.body = {
        code: -1,
        province: '',
        city: ''
      })
    }
  }
  @get('/province')
  async getProvinces(ctx, next) {
    let provinces = await Province.find({}, '-_id id name').exec()
    ctx.body = {
      code: provinces.length ? 0 : -1,
      province: provinces.length ? provinces : []
    }
  }

  @get('/province/:id')
  async getProvince(ctx, next) {
    let province = await Province.findOne({id: ctx.params.id}).exec()
    ctx.body = {
      code: province ? 0 : -1,
      city: province ? province.city : ''
    }
  }

  @get('/del')
  async del(ctx, next) {
    await Province.remove({}, ).exec()
    await City.remove({}).exec()
    ctx.body = {
      code:0 
    }
  }


  @get('/city')
  async getCity(ctx, next) {
    let city = await City.find({}, '-_id -areas').exec()
    ctx.body = {
      code: city.length ? 0 : -1,
      city: city.length ? city : []
    }
  }

  @get('/area')
  async getArea(ctx, next) {
    let city = await City.findOne({name: {$regex: ctx.query.city}},'-_id').exec()
    ctx.body = {
      code: city !== null ? 0 : -1,
      city: city !== null ? city : {}
    }
  }
}